package com.erp.order.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.web.oldDomain.BaseEntity;
import com.ruoyi.order.api.domain.ErpSellerChildOrder;
import com.ruoyi.order.api.domain.ErpSellerOrder;
import com.ruoyi.order.api.domain.ErpSellerChildOrderExtend;
import com.ruoyi.order.api.domain.ErpSellerOrderLog;
import com.erp.order.domain.vo.ErpSellerStoreProductEvaluationVo;
import com.ruoyi.common.core.enums.OrderLogType;
import com.ruoyi.common.core.enums.OrderProcessFlag;
import com.erp.order.mapper.ErpSellerChildOrderExtendMapper;
import com.erp.order.mapper.ErpSellerChildOrderMapper;
import com.erp.order.mapper.ErpSellerOrderMapper;
import com.erp.order.service.IErpSellerChildOrderService;
import com.erp.order.service.IErpSellerOrderLogService;
import com.erp.order.service.IErpSellerOrderService;
import com.erp.order.service.IErpSellerStoreProductEvaluationService;
import com.ruoyi.ae.api.RemoteAeOrderAddrService;
import com.ruoyi.ae.api.domain.AeStoreOrderReceiptAddress;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.enums.ExpenseType;
import com.ruoyi.common.core.enums.FlowType;
import com.ruoyi.common.core.enums.PayType;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.DingDingPushUtil;
import com.ruoyi.common.core.utils.excelPic.ExcelUtils;
import com.ruoyi.common.core.web.oldPage.TableDataInfo;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.gather.api.RemoteCollectProductSkuService;
import com.ruoyi.gather.api.RemoteSellerStoreProductService;
import com.ruoyi.gather.api.domain.ErpSellerStoreProduct;
import com.ruoyi.gather.api.domain.ErpSellerStoreProductSku;
import com.ruoyi.order.api.domain.bo.ErpSellerStoreProductEvaluationBo;
import com.ruoyi.shop.api.RemoteSellerStoreService;
import com.ruoyi.shop.api.domain.ErpSellerStoreEmpower;
import com.ruoyi.system.api.RemoteCountryCodeService;
import com.ruoyi.system.api.domain.CountryTwoCode;
import com.ruoyi.wallet.api.RemoteWalletExpandService;
import com.ruoyi.wallet.api.RemoteWalletLogService;
import com.ruoyi.wallet.api.RemoteWalletService;
import com.ruoyi.wallet.api.domain.ErpSellerStoreWalletLog;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import com.erp.order.mapper.ErpSellerStoreProductEvaluationMapper;
import com.ruoyi.order.api.domain.ErpSellerStoreProductEvaluation;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URL;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 在线商品测评Service业务层处理
 *
 * @author erp
 * @date 2023-06-26
 */
@RequiredArgsConstructor
@Service
public class ErpSellerStoreProductEvaluationServiceImpl implements IErpSellerStoreProductEvaluationService {


    private final ErpSellerStoreProductEvaluationMapper baseMapper;
    private final RemoteSellerStoreProductService remoteSellerStoreProductService;
    private final RemoteCollectProductSkuService remoteCollectProductSkuService;
    private final RemoteSellerStoreService remoteSellerStoreService;
    private final IErpSellerOrderService iErpSellerOrderService;
    private final ErpSellerOrderMapper erpSellerOrderMapper;
    private final ErpSellerChildOrderExtendMapper erpSellerChildOrderExtendMapper;
    private final ErpSellerChildOrderMapper sellerChildOrderMapper;
    private final IErpSellerOrderLogService orderLogService;
    private final RemoteWalletService remoteWalletService;
    private final RemoteWalletExpandService remoteWalletExpandService;
    private final RemoteWalletLogService remoteWalletLogService;
    private final RemoteAeOrderAddrService remoteAeOrderAddrService;
    private final RemoteCountryCodeService remoteCountryCodeService;

    @Override
    public Integer doubtEvaluation(String country, Long storeId, String payTime, Long productCount, String skuCode) {
        Date date = DateUtil.parse(payTime, "yyyy-MM-dd HH:mm:ss");
        //往后推两天
        Date newDate = DateUtil.offset(date, DateField.DAY_OF_MONTH, 2);
        ErpSellerStoreProductEvaluation evaluation = baseMapper.selectOne(
                new LambdaQueryWrapper<ErpSellerStoreProductEvaluation>()
                        .eq(ErpSellerStoreProductEvaluation::getStoreId, storeId)
                        .eq(ErpSellerStoreProductEvaluation::getCountry, country)
                        .eq(ErpSellerStoreProductEvaluation::getNumber, productCount)
                        .eq(ErpSellerStoreProductEvaluation::getSkuCode, skuCode)
                        .ge(ErpSellerStoreProductEvaluation::getUpdateTime, date)
                        .le(ErpSellerStoreProductEvaluation::getUpdateTime, newDate)
                        .last("limit 1")
        );
        return evaluation != null? evaluation.getType() : -1;
    }

    /**
     * 查询在线商品测评
     */
    @Override
    public ErpSellerStoreProductEvaluationVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询在线商品测评列表
     */
    @Override
    public TableDataInfo<ErpSellerStoreProductEvaluationVo> queryPageList(ErpSellerStoreProductEvaluationBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ErpSellerStoreProductEvaluation> lqw = buildQueryWrapper(bo);
        Page<ErpSellerStoreProductEvaluationVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        List<ErpSellerStoreProductEvaluationVo> records = result.getRecords();
        if (ObjectUtils.isNotEmpty(records)) {
            records.forEach(vo -> {
                Long storeId = vo.getStoreId();
                ErpSellerStoreEmpower empower = remoteSellerStoreService.getCompriseDeleteById(storeId);
                String storeName = empower.getStoreName();
                vo.setStoreName(storeName);
                if (vo.getOrderId() != null) {
                    vo.setOrderStatus(1);
                } else {
                    vo.setOrderStatus(0);
                }
                if (vo.getIntlTrackingNo() != null) {
                    vo.setIntlTrackingNoStatus(1);
                } else {
                    vo.setIntlTrackingNoStatus(0);
                }
            });
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询在线商品测评列表
     */
    @Override
    public List<ErpSellerStoreProductEvaluationVo> queryList(ErpSellerStoreProductEvaluationBo bo) {
        LambdaQueryWrapper<ErpSellerStoreProductEvaluation> lqw = buildQueryWrapper(bo);
        List<ErpSellerStoreProductEvaluationVo> evaluationVoList = baseMapper.selectVoList(lqw);
        if (ObjectUtils.isNotEmpty(evaluationVoList)) {
            evaluationVoList.forEach(vo -> {
                Long storeId = vo.getStoreId();
                R<Object> sellerStoreInfoById = remoteSellerStoreService.getSellerStoreInfoById(storeId);
                ErpSellerStoreEmpower empower = JSONObject.parseObject(JSON.toJSONString(sellerStoreInfoById.getData()), ErpSellerStoreEmpower.class);
                String storeName = empower.getStoreName();
                vo.setStoreName(storeName);
                CountryTwoCode countryByCode = remoteCountryCodeService.getCountryByCode(vo.getCountry());
                if (countryByCode != null) {
                    vo.setCountry(countryByCode.getCountryCn());
                }
            });
        }
        return evaluationVoList;
    }

    private LambdaQueryWrapper<ErpSellerStoreProductEvaluation> buildQueryWrapper(ErpSellerStoreProductEvaluationBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ErpSellerStoreProductEvaluation> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getSellerStoreProductId() != null, ErpSellerStoreProductEvaluation::getSellerStoreProductId, bo.getSellerStoreProductId());
        lqw.eq(bo.getCollectProductId() != null, ErpSellerStoreProductEvaluation::getCollectProductId, bo.getCollectProductId());
        lqw.eq(bo.getStoreId() != null, ErpSellerStoreProductEvaluation::getStoreId, bo.getStoreId());
        lqw.eq(org.apache.commons.lang3.StringUtils.isNotBlank(bo.getSkuCode()), ErpSellerStoreProductEvaluation::getSkuCode, bo.getSkuCode());
        lqw.eq(org.apache.commons.lang3.StringUtils.isNotBlank(bo.getSellerSignerFullname()), ErpSellerStoreProductEvaluation::getSellerSignerFullname, bo.getSellerSignerFullname());
        lqw.eq(bo.getNumber() != null, ErpSellerStoreProductEvaluation::getNumber, bo.getNumber());
        lqw.eq(org.apache.commons.lang3.StringUtils.isNotBlank(bo.getUnitPrice()), ErpSellerStoreProductEvaluation::getUnitPrice, bo.getUnitPrice());
        lqw.eq(org.apache.commons.lang3.StringUtils.isNotBlank(bo.getTotalPrices()), ErpSellerStoreProductEvaluation::getTotalPrices, bo.getTotalPrices());
        lqw.eq(org.apache.commons.lang3.StringUtils.isNotBlank(bo.getErd()), ErpSellerStoreProductEvaluation::getErd, bo.getErd());
        lqw.eq(org.apache.commons.lang3.StringUtils.isNotBlank(bo.getHandlingFee()), ErpSellerStoreProductEvaluation::getHandlingFee, bo.getHandlingFee());
        lqw.eq(bo.getEvaluationTime() != null, ErpSellerStoreProductEvaluation::getEvaluationTime, bo.getEvaluationTime());
        lqw.eq(bo.getOrderId() != null, ErpSellerStoreProductEvaluation::getOrderId, bo.getOrderId());
        lqw.eq(org.apache.commons.lang3.StringUtils.isNotBlank(bo.getIntlTrackingNo()), ErpSellerStoreProductEvaluation::getIntlTrackingNo, bo.getIntlTrackingNo());
        lqw.eq(bo.getStatus() != null, ErpSellerStoreProductEvaluation::getStatus, bo.getStatus());
        lqw.eq(org.apache.commons.lang3.StringUtils.isNotBlank(bo.getHint()), ErpSellerStoreProductEvaluation::getHint, bo.getHint());
        lqw.eq(org.apache.commons.lang3.StringUtils.isNotBlank(bo.getRevision()), ErpSellerStoreProductEvaluation::getRevision, bo.getRevision());
        lqw.orderByDesc(ErpSellerStoreProductEvaluation::getCreateTime);
        Integer isCompany = bo.getIsCompany();
        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(11);
        if (isCompany == null || isCompany == 0) {
            lqw.notIn(ErpSellerStoreProductEvaluation::getType,list);
        }else {
            lqw.in(ErpSellerStoreProductEvaluation::getType,list);
        }
        return lqw;
    }

    //    /**
//     * 新增在线商品测评
//     */
    @Override
    public Boolean insertByBo(ErpSellerStoreProductEvaluationBo bo) {
        ErpSellerStoreProductEvaluation add = BeanUtil.toBean(bo, ErpSellerStoreProductEvaluation.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }
//
//    /**
//     * 修改在线商品测评
//     */
//    @Override
//    public Boolean updateByBo(ErpSellerStoreProductEvaluationBo bo) {
//        ErpSellerStoreProductEvaluation update = BeanUtil.toBean(bo, ErpSellerStoreProductEvaluation.class);
//        validEntityBeforeSave(update);
//        return baseMapper.updateById(update) > 0;
//    }
//
    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ErpSellerStoreProductEvaluation entity) {
        //TODO 做一些数据校验,如唯一约束
    }

//    /**
//     * 批量删除在线商品测评
//     */
//    @Override
//    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
//        if (isValid) {
//            //TODO 做一些业务上的校验,判断是否需要校验
//        }
//        return baseMapper.deleteBatchIds(ids) > 0;
//    }

    /**
     * 提交测评订单号
     *
     * @param orderNumber
     * @param evaluationId
     * @return
     */
    @Override
    public R<Object> submitOrderNumber(Long orderNumber, Long evaluationId) {
        if (orderNumber == null) {
            return R.fail("请填入订单号");
        }
        ErpSellerStoreProductEvaluation evaluation = baseMapper.selectById(evaluationId);
        if (evaluation == null) {
            return R.fail("该测评单不存在");
        }
        //提示备注
        String remark = new String();
        //在系统内查找订单
        ErpSellerOrder order = new ErpSellerOrder();
        order = erpSellerOrderMapper.selectOne(
                new LambdaQueryWrapper<ErpSellerOrder>().eq(ErpSellerOrder::getOrderId, orderNumber));
        if (order == null) {
            //系统内不存在
            //根据店铺id，拉取一遍对应时间的订单
//            iAeOrderService.getOrderList(evaluation.getStoreId().toString(), null, null);
            //再取一遍
//            order = erpSellerOrderMapper.selectOne(new LambdaQueryWrapper<ErpSellerOrder>().eq(ErpSellerOrder::getOrderId,orderNumber));
//            if (order == null) {
            return R.fail("当前未发现该订单,请稍后再填入");
//            }
        }
        //查找到订单了，有四种情况
        if (order.getErpInnerOrderStatus().equals("110")) {
            return R.ok("该订单号已经填入过，请勿重复提交");
        }

        Integer type = evaluation.getType();
        if (type == 1) {
            // 看是否提交了审核
            ErpSellerOrderLog orderLog = orderLogService.
                    queryByStatusIntroAndOrderId(OrderLogType.SubmitOrder.getInfo(), order.getOrderId());
            if (orderLog == null) {
                return R.fail("订单未提交审核，请联系客服通知客户提交订单");
            }
        }
        // 将订单号添加为记录表的备注
        ErpSellerStoreWalletLog storeWalletLog = remoteWalletLogService.getWalletLogByOrderNumber(evaluation.getId().toString());
        if (storeWalletLog != null) {
            storeWalletLog.setRemark(orderNumber + "");
            remoteWalletLogService.updateById(storeWalletLog);
        }
        if (order.getErpInnerOrderStatus().equals("901")) {
            //1、已作废的订单 改变状态为刷单中
            remark = "已改变该订单状态为'测评订单'";
            evaluation.setStatus(2);
            order.setErpInnerOrderStatus("110");

        } else {
            if (order.getErpInnerOrderStatus().equals("101")) {
                //1、未提交的订单 改变状态为刷单中
                remark = "已改变该订单状态为'测评订单'";
                evaluation.setStatus(2);
                order.setErpInnerOrderStatus("110");

            } else if (order.getErpInnerOrderStatus().equals("103") || order.getErpInnerOrderStatus().equals("105")) {
                //获取订单中所有子订单extend
                List<ErpSellerChildOrderExtend> erpSellerChildOrderExtends = erpSellerChildOrderExtendMapper.selectList(
                        new LambdaQueryWrapper<ErpSellerChildOrderExtend>().eq(ErpSellerChildOrderExtend::getOrderId, order.getOrderId())
                );
                if (erpSellerChildOrderExtends.size() != 0) {
                    //2、已提交但未采购，驳回+改变状态
                    remark = "该订单已被提交审核，目前已驳回该订单，并改变状态为'测评订单'";
                    if (order.getErpInnerOrderStatus().equals("105")) {
                        remark = "该订单采购完成，请与采购确认";
                    }
                    evaluation.setStatus(2);
                    //驳回订单;  用户测评下单驳回,公司测评不驳回
                    Long orderId = order.getOrderId();
                    if (type != 1) {
                        ErpSellerStoreWalletLog walletLog = remoteWalletLogService.getWalletLogByOrderNumber(orderId.toString());
                        if (walletLog != null) {
                            BigDecimal totalAmount = walletLog.getMoney();
                            R<Object> returnR = remoteWalletService.updateWallet(FlowType.INCOME.getCode(),
                                    ExpenseType.ORDERREFUND.getCode(), PayType.XT.getCode(), totalAmount, walletLog.getSellerId(),
                                    orderId.toString(), "测评订单退回采购成本");
                            if (returnR.getCode() == 200) {
                                orderLogService.createOrderLog(orderId, null, OrderLogType.EvaluationOrder,
                                        "订单暂未被采购过", OrderProcessFlag.Evaluation.getInfo(), "110");
                            } else {
                                return returnR;
                            }
                        }
                    }
                } else {
                    //3、已提交且已采购，提示曲悦进行人工流程
                    remark = "该订单目前已被提交审核，并已采购，请联系采购人员";
                    evaluation.setStatus(2);
                }
            } else if (!order.getErpInnerOrderStatus().equals("101") || !order.getErpInnerOrderStatus().equals("103") || !order.getErpInnerOrderStatus().equals("100")) {
                //3、已提交且已采购，提示曲悦进行人工流程
                remark = "请确认该订单状态";
                evaluation.setStatus(2);
            }
        }


        evaluation.setRemark(remark);
        evaluation.setOrderId(orderNumber);
        baseMapper.updateById(evaluation);
        if (evaluation.getStatus() != 2) {
            return R.fail(remark);
        } else {
            if (type != 1) {
                orderLogService.createOrderLog(orderNumber, null, OrderLogType.EvaluationOrder,
                        null, OrderProcessFlag.Evaluation.getInfo(), "110");
                iErpSellerOrderService.setInnerStatus(orderNumber, "110", "evaluation");
            }else {
                orderLogService.createOrderLog(orderNumber, null, OrderLogType.HasBeenPurchase,
                        null, OrderProcessFlag.CompanyEva.getInfo(), "105");
                iErpSellerOrderService.setInnerStatus(orderNumber, "105", "companyEva");
            }
            return R.ok(remark);
        }
    }

    /**
     * 填写国际运单号
     *
     * @param intlTrackingNo
     * @param evaluationId
     * @return
     */
    @Override
    public R<Object> submitIntlTrackingNo(String intlTrackingNo, Long evaluationId) {
        if (intlTrackingNo == null) {
            return R.fail("请填入运单号");
        }
        ErpSellerStoreProductEvaluation evaluation = baseMapper.selectById(evaluationId);
        if (evaluation == null) {
            return R.fail("该测评单不存在");
        }
        if (evaluation.getStatus() != 2 && evaluation.getStatus() != 5) {
            return R.fail("该测评单状态不为'待填写运单号'");
        }
        //填写单号后，需要进行声明发货
        evaluation.setIntlTrackingNo(intlTrackingNo);
        evaluation.setStatus(5);
        evaluation.setRemark("该测评单已保存运单号，待声明发货");
        baseMapper.updateById(evaluation);
        return R.ok("已保存运单号");
    }

    @Override
    public void exportEvaluatio(HttpServletResponse response, String ids) {
        //表格内数据
        ArrayList<List<Object>> data = new ArrayList<>();

        //生成标头
        List<Object> head = Arrays.asList("店名全称", "关键词", "产品主图","APP美元价格（sku）","sku属性","每天几单" ,"下单周期","优惠卷链接/原价/优惠码","下单物流选项", "下单国家","默认订单备注（A）", "特殊要求","产品链接","店铺链接");
        data.add(head);

        //获取数据
        List<String> idList = Arrays.stream(ids.split(",")).collect(Collectors.toList());
        List<ErpSellerStoreProductEvaluation> evaluations = baseMapper.selectByIdList(idList);

        //表格一行
        CountryTwoCode countryTwoCode = new CountryTwoCode();
        try {
            for (ErpSellerStoreProductEvaluation evaluationFor : evaluations) {
                if (evaluationFor.getStatus() == 0) {
                    evaluationFor.setStatus(1);
                    baseMapper.updateById(evaluationFor);
                }
                ArrayList<Object> evaluation = new ArrayList<>();
                //测评店铺
                evaluation.add(evaluationFor.getSellerSignerFullname());
                //关键词
                evaluation.add(evaluationFor.getKeyWord());
                //主图
                String productImg = evaluationFor.getProductImg();
                if (productImg != null) {
                    if (!productImg.startsWith("http")){
                        productImg = "https://file.pbb2c.com/" + productImg;
                    }
                    evaluation.add(new URL(productImg));
                } else {
                    evaluation.add(null);
                }
                //APP美元价格（sku）
                evaluation.add(evaluationFor.getSkuPrice());
                //sku
                evaluation.add(evaluationFor.getSkuSpec());
                //下单数量
                evaluation.add(evaluationFor.getNumber());

                //下单时间
                evaluation.add(evaluationFor.getEvaluationTime());
                //优惠码
                if (ObjectUtils.isEmpty(evaluationFor.getPreferentialCode())) {
                    evaluation.add("暂无优惠码");
                } else {
                    evaluation.add(evaluationFor.getPreferentialCode());
                }
                //下单物流选项
                evaluation.add("EMS");
                //下单国家
                CountryTwoCode countryByCode = remoteCountryCodeService.getCountryByCode(evaluationFor.getCountry());
                if (countryByCode != null) {
                    evaluation.add(countryByCode.getCountryCn());
                }
                //默认订单备注（A）
                if (ObjectUtils.isEmpty(evaluationFor.getLeaveInfo())) {
                    evaluation.add("暂无留言");
                } else {
                    evaluation.add(evaluationFor.getLeaveInfo());
                }

                //特殊要求
                evaluation.add("无");
                //产品链接
                evaluation.add(evaluationFor.getLink());
                //店铺链接
                evaluation.add(evaluationFor.getStoreLink());

                //存入表格
                data.add(evaluation);

                evaluations = new ArrayList<>();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        String date = DateUtil.today();
        ExcelUtils.export(response, "测评信息(" + date + ")", data);
    }

    @Override
    public void exportEvaluatioByMobile(HttpServletResponse response) {
        //表格内数据
        ArrayList<List<Object>> data = new ArrayList<>();

        //生成标头
        List<Object> head = Arrays.asList("测评店铺", "下单时间", "产品主图", "关键词", "产品链接", "下单国家", "sku", "下单数量", "优惠码", "是否留言");
        data.add(head);

        //获取数据
        List<ErpSellerStoreProductEvaluation> evaluations = baseMapper.selectList(
                new LambdaQueryWrapper<ErpSellerStoreProductEvaluation>().eq(ErpSellerStoreProductEvaluation::getStatus, 0)
        );

        //表格一行

        try {
            for (ErpSellerStoreProductEvaluation evaluationFor : evaluations) {
                if (evaluationFor.getStatus() == 0) {
                    evaluationFor.setStatus(1);
                    baseMapper.updateById(evaluationFor);
                }
                ArrayList<Object> evaluation = new ArrayList<>();
                //测评店铺
                evaluation.add(evaluationFor.getSellerSignerFullname());
                //下单时间
                evaluation.add(evaluationFor.getEvaluationTime());
                //主图
                if (evaluationFor.getProductImg() != null) {
                    evaluation.add(new URL(evaluationFor.getProductImg()));
                } else {
                    evaluation.add(null);
                }
                //关键词
                evaluation.add(evaluationFor.getKeyWord());
                //产品链接
                evaluation.add(evaluationFor.getLink());
                //下单国家
                evaluation.add(evaluationFor.getCountry());
                //sku
                evaluation.add(evaluationFor.getSkuSpec());
                //下单数量
                evaluation.add(evaluationFor.getNumber());
                //优惠码
                if (evaluationFor.getPreferentialCode() != null) {
                    evaluation.add(evaluationFor.getPreferentialCode());
                } else {
                    evaluation.add("暂无优惠码");
                }
                //是否留言
                if (evaluationFor.getLeaveInfo() != null) {
                    evaluation.add(evaluationFor.getLeaveInfo());
                } else {
                    evaluation.add("暂无留言");
                }

                //存入表格
                data.add(evaluation);

                evaluations = new ArrayList<>();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        String date = DateUtil.today();

//        ExcelUtils.export(response, "测评信息(" + date + ")", data);
    }

    @Override
    public R<Object> submitTotalAmount(String totalAmount, Long evaluationId) {

        ErpSellerStoreProductEvaluation evaluation = baseMapper.selectById(evaluationId);
        Long storeId = evaluation.getStoreId();
        R<Object> sellerStoreInfoById = remoteSellerStoreService.getSellerStoreInfoById(storeId);

        ErpSellerStoreEmpower storeEmpower = JSONObject.parseObject(JSONObject.toJSONString(sellerStoreInfoById.getData()), ErpSellerStoreEmpower.class);
        Long userId = storeEmpower.getUserId();
        BigDecimal amount = new BigDecimal(totalAmount);
        String remark = "";
        if (evaluation.getOrderId() != null) {
            remark = evaluation.getOrderId() + "";
        }
        Integer type = evaluation.getType();
        if (type != null && type == 1) { // 公司刷单
            userId = 1L;
        }
        R<Object> returnR = remoteWalletExpandService.updateEvaluationAmount(FlowType.DEDUCTION.getCode(),
                ExpenseType.EVALUATION.getCode(), PayType.CP.getCode(), userId, amount, remark);
        if (returnR.getCode() == 200) {
            evaluation.setTotalAmount(totalAmount);
            baseMapper.updateById(evaluation);
            return R.ok();
        }
        return returnR;
    }

    @Override
    public R<Object> sellerShipmentForEvaluation(Long evaluationId) {
        ErpSellerStoreProductEvaluation evaluation = baseMapper.selectById(evaluationId);

        return iErpSellerOrderService.sellerShipmentForOther(evaluation.getOrderId(),1);
    }

    /**
     * 红点提醒待测评订单
     *
     * @return
     */
    @Override
    public R<Object> redReminderForEvaluationOrder() {
        List<ErpSellerStoreProductEvaluation> erpSellerStoreProductEvaluations = baseMapper.selectList(new LambdaQueryWrapper<ErpSellerStoreProductEvaluation>()
                .eq(ErpSellerStoreProductEvaluation::getStatus, 0)
                .ne(ErpSellerStoreProductEvaluation::getType,1));
        return R.ok(erpSellerStoreProductEvaluations.size());
    }

    @Override
    public R<Object> redReminderCompany() {
        List<ErpSellerStoreProductEvaluation> erpSellerStoreProductEvaluations = baseMapper.selectList(new LambdaQueryWrapper<ErpSellerStoreProductEvaluation>()
                .eq(ErpSellerStoreProductEvaluation::getStatus, 0)
                .eq(ErpSellerStoreProductEvaluation::getType,1));
        return R.ok(erpSellerStoreProductEvaluations.size());
    }
    @Override
    public List<String> selectStoreList() {
        return baseMapper.selectStoreList();
    }

    @Override
    public R<Object> submit(ErpSellerStoreProductEvaluationBo bo) {
        Integer type = bo.getType();
        if (type == null) {
            type =  0;
        }
        bo.setType(type);
        // 判断用户钱包是否为负数
        Long userId = null;
        if (bo.getType() == 0) {
            userId = SecurityUtils.getUserId();
        }else {
            R<Object> sellerStoreInfoById = remoteSellerStoreService.getSellerStoreInfoById(bo.getStoreId());
            if (sellerStoreInfoById.getData() != null) {
                ErpSellerStoreEmpower storeEmpower = JSONObject.parseObject(JSONObject.toJSONString(sellerStoreInfoById.getData()), ErpSellerStoreEmpower.class);
                userId = storeEmpower.getUserId();
            }
        }
        if(type != 1 && type != 11) { // 公司刷单去除测评余额判断
            R<Object> evaluationWallet = remoteWalletExpandService.getEvaluationWallet(userId);
            Object data = evaluationWallet.getData();
            BigDecimal evaMoney = new BigDecimal(String.valueOf(data));
            if (evaMoney.compareTo(BigDecimal.ZERO) <= 0) {
                return R.fail("测评余额不足，不能提交测评,请充值");
            }
        }
        Long productSkuId = bo.getProductSkuId();
        ErpSellerStoreProductSku productSku = remoteSellerStoreProductService.getSkuById(productSkuId);
        // 在线产品id
        Long sellerStoreProductId = productSku.getSellerStoreProductId();
        bo.setSellerStoreProductId(sellerStoreProductId);
        // skuCode
        String skuCode = productSku.getSkuCode();
        if (bo.getSkuCode() == null)
            bo.setSkuCode(skuCode);
        // 店铺id
        R<Object> sellerStoreProductInfo = remoteSellerStoreProductService.getSellerStoreProductInfoById(sellerStoreProductId.toString());
        String toJSONString = JSONObject.toJSONString(sellerStoreProductInfo.getData());
        ErpSellerStoreProduct sellerStoreProduct = JSONObject.parseObject(toJSONString, ErpSellerStoreProduct.class);
        if (bo.getStoreId() == null)
            bo.setStoreId(sellerStoreProduct.getStoreId());
        //店铺全称
        //1、获取该店铺信息
        ErpSellerStoreEmpower store =  remoteSellerStoreService.getCompriseDeleteById(bo.getStoreId());
//        JSONObject.parseObject(JSONObject.toJSONString(sellerStoreInfoById.getData()), ErpSellerStoreEmpower.class);
        //2、获取该店铺的订单的最新一条信息
        ErpSellerOrder order = erpSellerOrderMapper.selectOne(
                new LambdaQueryWrapper<ErpSellerOrder>()
                        .eq(ErpSellerOrder::getSellerLoginId, store.getStoreUserName())
                        .orderByDesc(ErpSellerOrder::getCreateTime)
                        .last("limit 1")
        );
        if (order != null) {
            bo.setSellerSignerFullname(order.getSellerSignerFullname());
        }
        // 采集商品id
        bo.setCollectProductId(sellerStoreProduct.getCollectProductId());
        // sku主图
//        String skuImage = productSku.getSkuImage();
//        bo.setProductImg(skuImage);
        // 轮播图首张
        String imageURLs = sellerStoreProduct.getImageURLs();
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(imageURLs)) {
            String[] images = imageURLs.split(";");
            List<String> imageList = Arrays.stream(images).collect(Collectors.toList());
            String image = imageList.get(0);
            bo.setProductImg(image);
        }
        // 状态
        bo.setStatus(0);
        // 关键词
//        ErpSellerProductExpand productExpand = productExpandMapper.selectOne(new LambdaQueryWrapper<ErpSellerProductExpand>().eq(ErpSellerProductExpand::getSellerProductId, product.getSellerProductId()));
//        bo.setKeyWord(productExpand.getKeyword());

        R<Object> specBySkuCdeNew = remoteCollectProductSkuService.getSpecBySkuCodeNew(productSku.getSkuCode());
        bo.setSkuSpec(specBySkuCdeNew.getData().toString());

        insertByBo(bo);

        StringBuffer pushSb = new StringBuffer();
        pushSb.append("有新的测评单待处理 ：")
                .append("\n")//换行
                .append("测评店铺 :" + store.getStoreName() + "(" + bo.getSellerSignerFullname() + ")")
                .append("\n")//换行
                .append("测评商品skucode :" + bo.getSkuCode() + "(" + bo.getCollectProductId() + ")")
                .append("\n")//换行
                .append("测评商品关键词 :" + bo.getKeyWord());
        try {
            DingDingPushUtil.sendBySginTianZai(pushSb.toString(),"荆");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return R.ok(bo.getId());
    }

    /**
     * 作废测评单
     *
     * @param evaluationIds
     * @return
     */
    @Override
    public R<Object> invalidEvaluationOrder(String evaluationIds) {
        List<String> evaluationList = Arrays.asList(evaluationIds.split(","));
        Integer flag = 0;
        for (String evaluationId : evaluationList) {
            ErpSellerStoreProductEvaluation evaluation = baseMapper.selectById(evaluationId);
            if (evaluation == null) {
                return R.fail("该测评单不存在");
            }
            evaluation.setStatus(6);
            baseMapper.updateById(evaluation);
            flag++;
        }
        return R.ok("已作废" + flag + "个测评单");
    }

    /**
     * 标记测评单已线下声明发货
     *
     * @param evaluationId
     * @return
     */
    @Override
    public R<Object> evaluationOrderShipped(Long evaluationId) {
        ErpSellerStoreProductEvaluation evaluation = baseMapper.selectById(evaluationId);
        if (evaluation == null) {
            return R.fail("该测评单不存在");
        }
        evaluation.setStatus(7);
        evaluation.setRemark("该测评单用户已在线下手动声明发货");
        baseMapper.updateById(evaluation);
        Integer type = evaluation.getType();
        if (type != null && type == 1) {
            orderLogService.createOrderLog(evaluation.getOrderId(), null, OrderLogType.OfflineOrderSendGoods,
                    null, OrderProcessFlag.CompanyEva.getInfo(), "107");
            iErpSellerOrderService.setInnerStatus(evaluation.getOrderId(), "107", "companyEva");
        }
        return R.ok("该测评单用户已在线下手动声明发货");
    }

    @Override
    public R<Object> addEvaluationOrder(Long storeId, Long orderId) {
        // 先临时插入一条
        ErpSellerStoreProductEvaluation productEvaluation = new ErpSellerStoreProductEvaluation();
        productEvaluation.setStoreId(storeId);
        productEvaluation.setType(0);
        baseMapper.insert(productEvaluation);
        R<Object> pullOrder = null;
        try {
            pullOrder = submitOrderNumber(orderId, productEvaluation.getId());
        }catch (Exception e) {
            baseMapper.deleteById(productEvaluation);
            return R.fail("订单拉取异常");
        }

        if (pullOrder.getCode() != 200) {
            // 填写失败,删除临时记录
            baseMapper.deleteById(productEvaluation);
            return pullOrder;
        }

        // 拉取到了,将其余信息补充完整
        ErpSellerOrder order = erpSellerOrderMapper.selectOne(new LambdaQueryWrapper<ErpSellerOrder>()
                .eq(ErpSellerOrder::getOrderId, orderId));
        List<ErpSellerChildOrder> childOrderList = sellerChildOrderMapper.selectList(new LambdaQueryWrapper<ErpSellerChildOrder>()
                .eq(ErpSellerChildOrder::getOrderId, orderId));
        ErpSellerChildOrder childOrder = childOrderList.get(0);
        Long aeProductId = childOrder.getProductId();
        String skuCode = childOrder.getSkuCode();
        // 获取在线商品信息
        ErpSellerStoreProduct sellerStoreProduct = new ErpSellerStoreProduct();
        sellerStoreProduct.setAeProductId(aeProductId);
        R<Object> productInfo = remoteSellerStoreProductService.getSellerStoreProductInfo(sellerStoreProduct);
        ErpSellerStoreProduct product = JSONObject.parseObject(JSON.toJSONString(productInfo.getData()), ErpSellerStoreProduct.class);
        if (product != null) {

            // 在线产品id
            Long sellerStoreProductId = product.getId();
            productEvaluation.setSellerStoreProductId(sellerStoreProductId);

            // 采集商品id
            productEvaluation.setCollectProductId(product.getCollectProductId());
            // 轮播图首张
            String imageURLs = product.getImageURLs();
            if (StringUtils.isNotEmpty(imageURLs)) {
                String[] images = imageURLs.split(";");
                List<String> imageList = Arrays.stream(images).collect(Collectors.toList());
                String image = imageList.get(0);
                productEvaluation.setProductImg(image);
            }
            R<Object> specBySkuCdeNew = remoteCollectProductSkuService.getSpecBySkuCodeNew(skuCode);
            productEvaluation.setSkuSpec(specBySkuCdeNew.getData().toString());
        }

        // 国家
        AeStoreOrderReceiptAddress address = remoteAeOrderAddrService.getAddressByOrderId(orderId);
        if (address != null) {
            String country = address.getCountry();
            productEvaluation.setCountry(country);
        }

        // 数量
        Long productCount = childOrder.getProductCount();
        productEvaluation.setNumber(productCount);
        productEvaluation.setType(0);

        // skuCode
        productEvaluation.setSkuCode(skuCode);

        //获取该店铺的订单的最新一条信息
        productEvaluation.setSellerSignerFullname(order.getSellerSignerFullname());

        // 时间
        String gmtCreate = order.getGmtCreate();
        productEvaluation.setEvaluationTime(DateUtils.parseDate(gmtCreate));

        productEvaluation.setOrderId(orderId);

        baseMapper.updateById(productEvaluation);
        return R.ok();
    }

    @Override
    public ErpSellerStoreProductEvaluation getEvaluationByOrderId(Long orderId) {
        return baseMapper.selectOne(new LambdaQueryWrapper<ErpSellerStoreProductEvaluation>().eq(ErpSellerStoreProductEvaluation::getOrderId, orderId));
    }

    @Override
    public Boolean judgeSuspected(Long aeProductId, Long storeId) {
        // 找出来该商品最新的订单
        ErpSellerChildOrder childOrder = sellerChildOrderMapper.getLatestByProduct(aeProductId);
        if (childOrder == null) {
            return false;
        }
        // 找到在线商品id
        ErpSellerStoreProduct searchProduct = new ErpSellerStoreProduct();
        searchProduct.setAeProductId(aeProductId);
        R<Object> objectR = remoteSellerStoreProductService.getSellerStoreProductInfo(searchProduct);
        if (objectR.getCode() != 200) {
            return true;
        }
        // 获取国家
        AeStoreOrderReceiptAddress addressByOrderId = remoteAeOrderAddrService.getAddressByOrderId(childOrder.getOrderId());
        String country = addressByOrderId.getCountry();
        // 获取刷单
        List<ErpSellerStoreProductEvaluation> evaluation = baseMapper.selectList(new LambdaQueryWrapper<ErpSellerStoreProductEvaluation>()
                .eq(ErpSellerStoreProductEvaluation::getCountry, country)
                .like(ErpSellerStoreProductEvaluation::getLink, aeProductId));
        return evaluation.size() > 0;
    }

    @Override
    public Boolean sevenDaysEvaluation(Long aeProductId) {
        LocalDate now = LocalDate.now();
        LocalDate minus = now.minus(3, ChronoUnit.DAYS);
        List<ErpSellerStoreProductEvaluation> evaluationList = baseMapper.selectList(new LambdaQueryWrapper<ErpSellerStoreProductEvaluation>()
                .like(ErpSellerStoreProductEvaluation::getLink, aeProductId)
                .ge(BaseEntity::getCreateTime, minus));
        return evaluationList.size() > 0;
    }
}
